<script setup lang="ts">
import { useVbenDrawer } from '@vben/common-ui';
import { useVbenForm } from '#/adapter/form';
import { createApp, updateApp } from '#/api/core/app';
import { useTableForgeStore } from '#/store/tableforge';
import { message } from 'ant-design-vue';
import { computed } from 'vue';

const emit = defineEmits<{ reload: [] }>();

const tableForgeStore = useTableForgeStore();
const isUpdate = computed(() => !!drawerApi.getData()?.id);
const title = computed(() => isUpdate.value ? '修改应用' : '创建新应用');

const schema = [
  {
    fieldName: 'name',
    label: '应用名称',
    component: 'Input',
    required: true,
    componentProps: {
      placeholder: '请输入应用名称',
      maxlength: 50,
    },
    rules: 'required',
  },
  {
    fieldName: 'icon',
    label: '应用图标',
    component: 'Select',
    defaultValue: 'home',
    componentProps: {
      options: [
        { label: '首页', value: 'home' },
        { label: '用户', value: 'user' },
        { label: '设置', value: 'setting' },
        { label: '检查', value: 'check-circle' },
        { label: '箭头', value: 'arrow-right' }
      ],
    },
    rules: 'required',
  },
  {
    fieldName: 'spaceId',
    label: '所属空间',
    component: 'Select',
    componentProps: {
      placeholder: '请选择所属空间',
      options: [],
    },
    rules: 'selectRequired',
  },
];

const [BasicForm, formApi] = useVbenForm({
  schema,
  showDefaultActions: false,
  commonConfig: {
    formItemClass: 'col-span-2',
    componentProps: {
      class: 'w-full',
    },
  },
  layout: 'vertical',
  wrapperClass: 'grid-cols-2 gap-x-4',
});

const [BasicDrawer, drawerApi] = useVbenDrawer({
  onCancel: handleCancel,
  onConfirm: handleConfirm,
  async onOpenChange(isOpen) {
    if (!isOpen) {
      return null;
    }
    drawerApi.drawerLoading(true);

    // 重置表单
    await formApi.resetForm();

    // 如果是编辑模式，设置表单值
    const editData = drawerApi.getData();
    if (editData?.id) {
      await formApi.setValues(editData);
    }

    // 加载空间列表
    try {
      const spaces = await tableForgeStore.fetchSpaceList();
      if (spaces?.length > 0) {
        const options = spaces.map(space => ({
          label: space.name,
          value: space.id
        }));

        // 更新表单中的空间选项
        formApi.updateSchema([{
          fieldName: 'spaceId',
          componentProps: {
            options,
          },
        }]);

        // 如果是新建模式且没有选择空间，则默认选择第一个空间
        if (!isUpdate.value && !formApi.form.values.spaceId) {
          if (tableForgeStore.currentSpaceId) {
            formApi.setFieldValue('spaceId', tableForgeStore.currentSpaceId);
          } else if (spaces[0]?.id) {
            formApi.setFieldValue('spaceId', spaces[0].id);
          }
        }
      }
    } catch (error) {
      console.error('获取空间列表失败', error);
      message.error('获取空间列表失败');
    }

    drawerApi.drawerLoading(false);
  },
});

async function handleConfirm() {
  try {
    drawerApi.drawerLoading(true);
    const { valid } = await formApi.validate();
    if (!valid) {
      return;
    }
    const values = await formApi.getValues();
    const data = {
      name: values.name,
      description: values.description || '',
      icon: values.icon || 'home',
      spaceId: values.spaceId,
      displayOrder: values.displayOrder || 0
    };

    if (isUpdate.value) {
      await updateApp(drawerApi.getData().id, data);
      message.success('应用修改成功');
    } else {
      await createApp(data);
      message.success('应用创建成功');
    }

    emit('reload');
    await handleCancel();
  } catch (error) {
    console.error(isUpdate.value ? '修改应用失败' : '创建应用失败', error);
    message.error(isUpdate.value ? '修改应用失败' : '创建应用失败');
  } finally {
    drawerApi.drawerLoading(false);
  }
}

async function handleCancel() {
  drawerApi.close();
  await formApi.resetForm();
}
</script>

<template>
  <BasicDrawer :close-on-click-modal="false" :title="title" class="w-[600px]">
    <BasicForm />
  </BasicDrawer>
</template>
